package setting

import (
	"flag"
	"fmt"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

var Conf = new(AppConfig)

type AppConfig struct{
	Name    		string  `mapstructure:"name"`
	Version 		string  `mapstructure:"version"`
	Port 			string 	`mapstructure:"port"`
	StartTime  		string 	`mapstructure:"start_time"`
	MachineId  		uint16 	`mapstructure:"machineid"`
	*LogConfig    			`mapstructure:"log"`
	*MysqlConfig  			`mapstructure:"mysql"`
	*RedisConfig  			`mapstructure:"redis"`
}
type LogConfig struct{
	Level 			string  `mapstructure:"level"`
	Filename 		string  `mapstructure:"filename"`
	MaxSize 		int  	`mapstructure:"max_size"`
	MaxAge 			int  	`mapstructure:"max_age"`
	MaxBackups 		int  	`mapstructure:"max_backups"`
}
type MysqlConfig struct{
	HostSql 		string  `mapstructure:"host"`
	PortSql 		int  	`mapstructure:"port"`
	User 			string  `mapstructure:"user"`
	PasswordSql 	string  `mapstructure:"password"`
	DBname 			string  `mapstructure:"dbname"`
	SetmaxidleConns int  	`mapstructure:"setmaxidle_conns"`
	SetmaxopenConns int   	`mapstructure:"setmaxopen_conns"`
}
type RedisConfig struct{
	Host 			string  `mapstructure:"host"`
	PortRE 			int  	`mapstructure:"port"`
	DB 				int  	`mapstructure:"db"`
	Password 		string  `mapstructure:"password"`
	PoolSize 		int  	`mapstructure:"pool_size"`
	MinidleConns 	int  	`mapstructure:"minidle_conns"`
}
func Init() (err error) {
	var flsfile string
	flag.StringVar(&flsfile, "flsfile", "./config.yaml", "姓名")
	flag.Parse()
	viper.SetConfigFile(flsfile) // 指定配置文件路径
	// viper.SetConfigName("config")
	// viper.AddConfigPath(".")
	err = viper.ReadInConfig()               // 读取配置信息
	if err != nil {                           // 读取配置信息失败
		panic(fmt.Errorf("Fatal error config file:%v", err))
	}
	//将读取的配置信息保存至全局变量Conf
	if err := viper.Unmarshal(Conf); err != nil {
		panic(fmt.Errorf("unmarshal conf failed, err:%v", err))
	}
	// 监控配置文件变化
	viper.WatchConfig()
	// 注意！！！配置文件发生变化后要同步到全局变量Conf
	viper.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("配置文件被人修改...")
		if err := viper.Unmarshal(Conf); err != nil {
			panic(fmt.Errorf("unmarshal conf failed, err:%v", err))
		}
	})
	return
}